package com.cloud.lan.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.LanTagCfgReq;
import com.cloud.lan.dao.LanTagCfgMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.base.ListResponse;
import com.cloud.lan.entity.model.dataobject.LanTagCfgDO;
import com.cloud.lan.service.ILanTagCfgService;
import com.cloud.lan.service.ILanTagUserService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhouquan on 2022/4/14.
 */
@Slf4j
@Service
public class LanTagCfgServiceImpl extends ServiceImpl<LanTagCfgMapper, LanTagCfgDO> implements ILanTagCfgService {

    @Resource
    private LanTagCfgMapper lanTagCfgMapper;

    @Autowired
    private ILanTagUserService iLanTagUserService;

    @Override
    public ListResponse<List<LanTagCfgDO>> queryTagCfgList(LanTagCfgReq req) {
        log.info("标签配置.查询.req:[{}]", JSON.toJSONString(req));
        ListResponse listResponse = new ListResponse();
        LambdaQueryWrapper<LanTagCfgDO> qw = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(req.getTagCodes())){
            List<String> tagCodeList = Stream.of(req.getTagCodes().split(";")).collect(Collectors.toList());
            qw.in(LanTagCfgDO::getTagCode,tagCodeList);
        }
        if(StringUtils.isNotBlank(req.getTagName())){
            qw.like(LanTagCfgDO::getTagName,req.getTagName());
        }
        qw.eq(LanTagCfgDO::getIsDeleted,0);

        List<LanTagCfgDO> list = lanTagCfgMapper.selectList(qw);
        listResponse.setData(list);
        if(CollectionUtils.isNotEmpty(list)){
            listResponse.setNums(list.size());
            //查找标签人数
            list.stream().forEach(tagCfgDO -> {
                int totalNums = iLanTagUserService.queryTagUserNums(tagCfgDO);
                tagCfgDO.setTagUserNums(totalNums);
            });


        }
        log.info("标签配置.查询.res:[{}]", JSON.toJSONString(listResponse));
        return listResponse;
    }

    @Override
    public BaseResponse<Object> add(LanTagCfgReq req) {
        log.info("标签配置.新增.req:[{}]", JSON.toJSONString(req));
        LanTagCfgDO tagCfgDO = new LanTagCfgDO();
        BeanUtil.copyProperties(req, tagCfgDO);
        tagCfgDO.setUpdateTime(new Date());
        lanTagCfgMapper.insert(tagCfgDO);
        return BaseResponse.success();
    }
}
